package com.xuyang.server;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xuyang.utils.MySqlHelper;

/**
 * Servlet implementation class BorrowBookServlet
 */
public class BorrowBookServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "charset=utf-8");
		String bookId=request.getParameter("bookId");
		String userName=request.getParameter("userName");
		//从已借图书中获取当前图书是否已经被借出
		boolean isBorrow=MySqlHelper.getInstance().isBorrow("select * from bookborrow where bookId=? and returned=0", bookId);
		//如果已经被借则返回已经借出
		if (isBorrow) {
			response.getWriter().print("borrowed");
		}else {
			boolean isOk=MySqlHelper.getInstance().update("insert into bookborrow(bookId,userName,browTime) values(?,?,?)", new Object[]{bookId,userName,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())});
			//预约成功则修改该图书状态
			if (isOk) {
				MySqlHelper.getInstance().update("update bookstacks set state=0 where id=?", new Object[]{bookId});
				response.getWriter().print("ok");
			}else {
				response.getWriter().print("error");
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response); 
	}

}
